import axios from "axios";

import { ElMessage } from 'element-plus'
import router from '../router'
// 创建一个axios实例
const request = axios.create({
    baseURL: '/api', 
    timeout: 50000 // 请求超时
});
// 请求拦截器
request.interceptors.request.use(
    config => {
        let loginUser = JSON.parse(localStorage.getItem('loginUser'))
        if (loginUser) {
            config.headers.token = loginUser.token
        }
        return config;
    }
);
// axios的响应response拦截器
request.interceptors.response.use(
    response => {
        return response.data
    },
    (error) => {
        if (error.response.status === 401) {
            ElMessage.error('登录失效, 请重新登录')
            router.push('/login')
          }else{
            ElMessage.success('接口访问异常')
          }
        return Promise.reject(error)
    }
)

export default request